// App.js 或者任何一个全局组件
import { useEffect, useState } from 'react';
import { Spin } from 'antd';
import pubsub, { AXIOS_LOADING_SHOW, AXIOS_LOADING_HIDE } from '@/utils/pubsub';

interface LoadingIndicatorProps {
	children?: React.ReactNode;
}
function LoadingIndicator({ children }: LoadingIndicatorProps) {
	const [isLoading, setIsLoading] = useState(false);

	let loadingIndex = 0;

	useEffect(() => {
		pubsub.on(AXIOS_LOADING_SHOW, (...args) => {
			loadingIndex++;
			if (loadingIndex == 1) {
				setIsLoading(true);
			}			
		});

		pubsub.on(AXIOS_LOADING_HIDE, (...args) => {
			loadingIndex--;
			if (loadingIndex == 0) {
				setIsLoading(false);
			}
		});
	});

	return isLoading ? <Spin children={children}></Spin> : null;
}

export default LoadingIndicator;
